package Servlet.Order;

import DataBase.DataBase;
import com.github.wxpay.sdk.MyConfig;
import com.github.wxpay.sdk.WXPay;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static com.github.wxpay.sdk.WXPayUtil.MD5;

public class AfterPayServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession HS = req.getSession();
        String out_trade_no = HS.getAttribute("out_trade_no").toString();
        String orderID = HS.getAttribute("orderID").toString();
        if (getStatus(out_trade_no)){
            System.out.println("支付成功");
            DataBase.SuccessPay(orderID);
            resp.sendRedirect("Order/SuccessPay.jsp");
            HS.setAttribute("out_trade_no",null);
            HS.setAttribute("orderCost",null);
        }
        else {
            System.out.println("支付失败");
            resp.sendRedirect("Order/FailedPay.jsp");
        }
    }

    public boolean getStatus(String out_trade_no){
        try {
            String stringRandom = String.valueOf((int)(Math.random() * 100000));

            Map<String, String> dataMap = new HashMap<>();
            dataMap.put("appid", "wx8397f8696b538317");
            dataMap.put("mch_id", "1473426802");
            dataMap.put("out_trade_no", out_trade_no);
            dataMap.put("nonce_str", stringRandom);

            String string = "appid=wx8397f8696b538317&mch_id=1473426802&out_trade_no=" + out_trade_no + "&nonce_str=" + stringRandom + "&key=T6m9iK73b0kn9g5v426MKfHQH7X8rKwb";
            String sign = MD5(string).toUpperCase();
            dataMap.put("sign", sign);

            MyConfig wxPayConfig = new MyConfig();

            WXPay wxPay = new WXPay(wxPayConfig);
            Map<String, String> orderQuery = wxPay.orderQuery(dataMap);
            if(orderQuery.get("trade_state").equalsIgnoreCase("SUCCESS")){
                return true;
            }

            return false;
        }catch (Exception ex){
            System.out.println("getStatusException");
        }
        return false;
    }
}
